package com.itheima.exam.service.impl;

import com.itheima.exam.pojo.Warehouse;
import com.itheima.exam.pojo.WarehouseRestock;
import com.itheima.exam.mapper.WarehouseMapper;
import com.itheima.exam.service.WarehouseService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class WarehouseServiceImpl implements WarehouseService {
    @Resource
    private WarehouseMapper warehouseMapper;

    /**
     * 查询仓库列表
     *
     * @param list 查询条件
     * @return 仓库列表
     */
    @Override
    public List<Warehouse> listWarehouses(Map<String, Object> list) {
        return warehouseMapper.listWarehouses(list);
    }


    /**
     * 出库
     *
     * @param restock 出库数量
     * @return 出库结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public List<WarehouseRestock> outWarehouse(Integer restock) {
        // 如果出库数量为 null 或小于等于 0，直接返回空列表
        if (restock == null || restock <= 0) {
            return new ArrayList<>();
        }

        // 获取所有仓库列表并按库存从大到小排序
        List<Warehouse> warehouses = warehouseMapper.listWarehouses(null)
                .stream()
                .sorted(Comparator.comparing(Warehouse::getStock).reversed())
                .collect(Collectors.toList());

        List<WarehouseRestock> restockResults = new ArrayList<>();

        // 遍历仓库列表进行出库操作
        for (Warehouse warehouse : warehouses) {
            // 如果剩余出库数量为 0，停止出库操作
            if (restock <= 0) {
                break;
            }

            // 计算当前仓库的出库数量
            int restockAmount = Math.min(restock, warehouse.getStock());

            // 更新剩余出库数量
            restock -= restockAmount;

            // 计算仓库剩余库存
            int balance = warehouse.getStock() - restockAmount;

            // 更新仓库库存
            warehouseMapper.updateStock(warehouse.getId(), balance);

            // 记录出库结果
            restockResults.add(WarehouseRestock.builder()
                    .warehouseName(warehouse.getWarehouseName())
                    .restock(restockAmount)
                    .balance(balance)
                    .build());
        }

        // 返回出库结果列表
        return restockResults;
    }
}
